import { Injectable, Logger } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';

@Injectable()
export class MailService {
  private readonly logger = new Logger(MailService.name);
  private transporter: nodemailer.Transporter;

  constructor(
    private mailerService: MailerService,
    private configService: ConfigService,
  ) {
    this.transporter = nodemailer.createTransport({
      host: this.configService.get('MAIL_HOST'),
      port: this.configService.get('MAIL_PORT'),
      secure: this.configService.get('MAIL_SECURE'),
      auth: {
        user: this.configService.get('MAIL_USER'),
        pass: this.configService.get('MAIL_PASS'),
      },
    });

    // 在服务初始化时打印邮件配置
    this.logger.debug('Mail Service initialized with config:', {
      host: this.configService.get('MAIL_HOST'),
      port: this.configService.get('MAIL_PORT'),
      secure: this.configService.get('MAIL_SECURE'),
      user: this.configService.get('MAIL_USER'),
    });
  }

  async sendPasswordResetEmail(email: string, resetToken: string, username: string) {
    try {
      const frontendUrl = this.configService.get<string>('FRONTEND_URL');
      this.logger.debug(`Sending password reset email to ${email}`);
      this.logger.debug(`Frontend URL: ${frontendUrl}`);
      
      const resetUrl = `${frontendUrl}/auth/reset-password?token=${resetToken}`;

      await this.mailerService.sendMail({
        to: email,
        subject: '重置密码 - Monday项目管理系统',
        template: 'reset-password',
        context: {
          username,
          resetUrl,
          year: new Date().getFullYear(),
        },
      });
      
      this.logger.debug(`Password reset email sent successfully to ${email}`);
    } catch (error) {
      this.logger.error(`Failed to send password reset email to ${email}:`, error);
      throw error;
    }
  }

  async sendVerificationEmail(email: string, verificationToken: string, username: string) {
    try {
      const frontendUrl = this.configService.get<string>('FRONTEND_URL');
      this.logger.debug(`Sending verification email to ${email}`);
      this.logger.debug(`Frontend URL: ${frontendUrl}`);
      
      const verifyUrl = `${frontendUrl}/auth/verify-email?token=${verificationToken}`;

      await this.mailerService.sendMail({
        to: email,
        subject: '验证邮箱 - Monday项目管理系统',
        template: 'verify-email',
        context: {
          username,
          verifyUrl,
          year: new Date().getFullYear(),
        },
      });
      
      this.logger.debug(`Verification email sent successfully to ${email}`);
    } catch (error) {
      this.logger.error(`Failed to send verification email to ${email}:`, error);
      throw error;
    }
  }

  // 发送工作区邀请邮件
  async sendWorkspaceInvitation(params: {
    to: string;
    workspaceName: string;
    invitationLink: string;
  }) {
    const { to, workspaceName, invitationLink } = params;

    await this.transporter.sendMail({
      from: this.configService.get('MAIL_FROM'),
      to,
      subject: `邀请您加入工作区 ${workspaceName}`,
      html: `
        <h2>工作区邀请</h2>
        <p>您被邀请加入工作区 ${workspaceName}</p>
        <p>请点击下面的链接接受邀请：</p>
        <p><a href="${invitationLink}">接受邀请</a></p>
        <p>如果您无法点击链接，请复制以下地址到浏览器打开：</p>
        <p>${invitationLink}</p>
        <p>此邀请链接将在7天后过期。</p>
        <p>如果您没有注册账号，请先注册后再接受邀请。</p>
        <p>如果您没有申请加入该工作区，请忽略此邮件。</p>
      `,
    });
  }
} 